package com.poizon.infrastructure.lock.starter.redisson.util;

import cn.hutool.core.lang.Assert;
import com.poizon.infrastructure.lock.core.util.AbstractLock;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

import static com.poizon.infrastructure.lock.core.enums.LockConstants.LOCK_NAME_PREFIX;

@Slf4j
@AllArgsConstructor
public class RedissonLock extends AbstractLock {
    private RedissonClient redissonClient;

    @SneakyThrows
    @Override
    protected boolean tryLockImpl(String lockName, Long waitTime, Long timeout, TimeUnit timeUnit) {
        Assert.notBlank(lockName);
        Assert.notNull(waitTime);
        Assert.notNull(timeout);
        Assert.notNull(timeUnit);

        RLock lock = redissonClient.getLock(LOCK_NAME_PREFIX + lockName);
        return lock.tryLock(waitTime, timeout, timeUnit);
    }

    @Override
    protected void unLockImpl(String lockName) {
        Assert.notBlank(lockName);

        lockName = LOCK_NAME_PREFIX + lockName;
        RLock lock = redissonClient.getLock(lockName);

        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
            return;
        }

        log.warn(">锁业务超时,锁已释放,锁名称={}", lockName);
    }
}
